package B刷题.链表;

import java.util.Comparator;
import java.util.PriorityQueue;


/**
 * @author wei.zhao
 * @description: 剑指 Offer II 078.合并排序链表
 * @date 2022年11月29日 16:15
 */
public class Code04_MergeKLists {

    public ListNode mergeKLists(ListNode[] lists) {
        ListNode head = null;
        ListNode cur = null;
        PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(e -> e.val));
        for (ListNode node : lists) {
            if (null != node) {
                queue.add(node);
            }
        }
        if (queue.size()==0){
            return null;
        }
        while (!queue.isEmpty()) {
            ListNode poll = queue.poll();
            if (head == null) {
                head = poll;
                cur = poll;
            } else {
                cur.next = poll;
                cur = poll;
            }
            if (poll.next != null) {
                queue.add(poll.next);
            }
        }
        cur.next = null;
        return head;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

    }

}
